package club.justwill.single.helper;

import club.justwill.single.bean.UserInvite;
import club.justwill.single.model.SessionState;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

import java.io.IOException;

/**
 * Created by xiangnan on 15-12-24.
 */
@Component
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class SmsHelper extends BaseHelper{

    private static final Logger logger = LoggerFactory.getLogger(SmsHelper.class);

    @Value("${sms.url}")
    private String url;

    @Value("${sms.user}")
    private String accunt;

    @Value("${sms.key}")
    private String password;
   /* public String sendInvitationCode(UserInvite inviter, String inviteePhone){
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(url);
        String code = "";
        String msg = "";
        String smsid = "";
        client.getParams().setContentCharset("UTF-8");
        method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=UTF-8");

        String invitationCode = inviter.getInvitationCode();
        String content = new String("您的朋友邀请您参加活动：邀请码为" + invitationCode);
        NameValuePair[] data = {
                new NameValuePair("account", accunt),
                new NameValuePair("password", password),
//                new NameValuePair("password", Util.StringUtil.MD5Encode("andi2015dxjx")),
                new NameValuePair("mobile", inviteePhone),
                new NameValuePair("content", content),
        };
        method.setRequestBody(data);
        try {
            client.executeMethod(method);
            String SubmitResult =method.getResponseBodyAsString();
            Document doc = DocumentHelper.parseText(SubmitResult);
            Element root = doc.getRootElement();
            code = root.elementText("code");
            msg = root.elementText("msg");
            smsid = root.elementText("smsid");


            logger.info(code);
            logger.info("Sms access Message: [{}].", msg);
            logger.info(smsid);

            if(!"2".equals(code)){
                logger.error("send message error");
            }
        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return code;
    }*/
    public String sendAuthCode(SessionState sessionState){
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(url);
        String code = "";
        String msg = "";
        String smsid = "";

        //client.getParams().setContentCharset("GBK");
        client.getParams().setContentCharset("UTF-8");
        method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=UTF-8");


        int mobile_code = (int)((Math.random()*9+1)*100000);

        sessionState.setAuthCode(mobile_code);
        sessionState.setExpire(System.currentTimeMillis() + fiveMinutes);

        //System.out.println(mobile);

        String content = new String("您的手机验证码是：" + mobile_code + "。如非本人操作请致电："+ "400-028-8977" + "。");
        NameValuePair[] data = {
                new NameValuePair("account", accunt),
                new NameValuePair("password", password),
//                new NameValuePair("password", Util.StringUtil.MD5Encode("andi2015dxjx")),
                new NameValuePair("mobile", sessionState.getMobile()),
                new NameValuePair("content", content),
        };

        method.setRequestBody(data);


        try {
            client.executeMethod(method);

            String SubmitResult =method.getResponseBodyAsString();

            //System.out.println(SubmitResult);

            Document doc = DocumentHelper.parseText(SubmitResult);
            Element root = doc.getRootElement();


            code = root.elementText("code");
            msg = root.elementText("msg");
            smsid = root.elementText("smsid");


            logger.info(code);
            logger.info("Sms access Message: [{}].", msg);
            logger.info(smsid);

            if(!"2".equals(code)){
                logger.error("send message error");
            }

        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return code;
    }
}
